package org.example.airesumescoring.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class DeepSeekApiClientService implements AIService {
    @Value("${deepseek.api.key}")
    private String apiKey;
    @Value("${deepseek.api.url}")
    private String apiUrl;

    @Override
    public String analyzeResume(String resumeText) throws Exception {
        URL url = new URL(apiUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Authorization", "Bearer " + apiKey);
        connection.setDoOutput(true);

        Map<String, Object> body = new HashMap<>();
        body.put("model", getModelName());

        List<Map<String, String>> messages = new ArrayList<>();
        messages.add(Map.of(
                "role", "system",
                "content", "你是简历分析专家，请分析以下简历内容并以JSON格式返回姓名、联系方式、教育经历、工作经历、技能、反馈"
        ));
        messages.add(Map.of("role", "user", "content", resumeText));

        body.put("messages", messages);
        body.put("stream", false);

        String requestBody = new ObjectMapper().writeValueAsString(body);

        try (OutputStream os = connection.getOutputStream()) {
            os.write(requestBody.getBytes(StandardCharsets.UTF_8));
        }

        if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
            throw new RuntimeException("API调用失败，响应码: " + connection.getResponseCode());
        }

        try (BufferedReader in = new BufferedReader(
                new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
            StringBuilder response = new StringBuilder();
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            return response.toString();
        }
    }

    @Override
    public String resumeDialogue(String context, String question) throws Exception {
        URL url = new URL(apiUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Authorization", "Bearer " + apiKey);
        connection.setDoOutput(true);

        Map<String, Object> body = new HashMap<>();
        body.put("model", getModelName());

        List<Map<String, String>> messages = new ArrayList<>();
        messages.add(Map.of(
                "role", "system",
                "content", "你是一个专业的职业顾问，基于用户提供的简历内容和对话历史，回答用户关于职业发展的问题。回答要专业、具体，并给出合理的建议。"
        ));
        messages.add(Map.of("role", "user", "content", context));
        messages.add(Map.of("role", "user", "content", question));

        body.put("messages", messages);
        body.put("temperature", 0.7); // 控制创造性
        body.put("max_tokens", 1000); // 限制响应长度

        String requestBody = new ObjectMapper().writeValueAsString(body);

        try (OutputStream os = connection.getOutputStream()) {
            os.write(requestBody.getBytes(StandardCharsets.UTF_8));
        }

        if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
            throw new RuntimeException("API调用失败，响应码: " + connection.getResponseCode());
        }

        try (BufferedReader in = new BufferedReader(
                new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
            StringBuilder response = new StringBuilder();
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            return response.toString();
        }

    }

    private String getModelName() {
        return "deepseek-chat"; // 保持原有模型名称，但集中管理
    }
}